#!/usr/bin/env python
# coding: latin-1

import sys
import tos
import math

AM_OSCILLOSCOPE = 0x93

class OscilloscopeMsg(tos.Packet):
	def __init__(self, packet = None):
		tos.Packet.__init__(self,
							[('version',  'int', 2),
							 ('interval', 'int', 2),
							 ('id',       'int', 2),
							 ('count',    'int', 2),
							 ('readings', 'blob', None),
							 ('id_readings', 'int', 2)],
							packet)
def raw_to_kelvin(ADC):
	if ADC == 0:
		return None
	a = 0.001010024
	b = 0.000242127
	c = 0.000000146
	R1 = 10000
	ADC_FS = 1023.
	Rth = R1 * float(ADC_FS - ADC) / ADC

	if Rth < 0:
		return None

	ln_Rth = math.log(Rth)
	TK = 1. / (a + (b * ln_Rth) + (c * (ln_Rth * ln_Rth * ln_Rth)))
	return TK


def kelvin_to_celcius(tk):
	return tk - 273.15


def raw_to_celcius(ADC):
	tk = raw_to_kelvin(ADC)

	if tk == None:
		return 0

	return kelvin_to_celcius(tk)	


if '-h' in sys.argv:
	print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
	sys.exit()

am = tos.AM()

while True:
	p = am.read()
	if p and p.type == AM_OSCILLOSCOPE:
		msg = OscilloscopeMsg(p.data)
		soma = 0
		for (i,j) in zip(msg.readings[::2], msg.readings[1::2]):
			soma = soma + (i<<8 | j)
		soma = soma/10
		
		if msg.id_readings == 1:
			tc = raw_to_celcius(soma)		
			print "O  valor do nó ",msg.id," recebeu ", msg.count," e a media da temperatura é ", tc, "ºC", 
		else:
			print "O  valor do nó ",msg.id," recebeu ", msg.count," e a media da luminosidade é ", soma 
